package thesis.filesharing.bo.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import thesis.filesharing.bo.SubjectBO;
import thesis.filesharing.common.exception.functional.InvalidArgumentException;
import thesis.filesharing.common.exception.functional.ObjectNotFoundException;
import thesis.filesharing.dao.SubjectDAO;
import thesis.filesharing.model.Subject;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@Service
public class SubjectBOImpl implements SubjectBO {
	
	@Autowired
	private SubjectDAO subjectDAO;
	
	@Override
	public List<Subject> listSubjects(int page, int pageSize) {
		if (page <= 0 || pageSize <= 0) {
			throw new InvalidArgumentException();
		}
		return subjectDAO.listSubjects(page, pageSize);
	}

	@Override
	public int countSubjects() {
		return subjectDAO.countSubjects();
	}

	@Override
	public Subject findSubjectById(String subjectId) {
		return subjectDAO.findSubjectById(subjectId);
	}

	@Override
	public Subject saveSubject(Subject subject) {
		return subjectDAO.saveSubject(subject);
	}

	@Override
	public void deleteSubject(String key) {
		Key subjectKey = KeyFactory.stringToKey(key);
		Subject s = subjectDAO.findSubjectByKey(subjectKey);
		if (s == null) {
			throw new ObjectNotFoundException(new Exception("Subject could not be found"), Subject.class);
		}
		subjectDAO.deleteSubject(subjectKey);
	}

	@Override
	public Subject updateSubject(Subject subject) {
		return subjectDAO.updateSubject(subject);
	}

	@Override
	public boolean checkUpdatedSubjectExisted(String key, String subjectId) {
		return subjectDAO.checkUpdatedSubjectExisted(KeyFactory.stringToKey(key), subjectId);
	}

	@Override
	public Subject findSubjectByKey(String key) {
		return subjectDAO.findSubjectByKey(KeyFactory.stringToKey(key));
	}
}
